class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]
  skip_before_action :redirect_if_not_login, only: [:new, :create]

  def index
    page = params[:page] || 1
    per_page = params[:per_page] || 20
    @objs = @model.paginate(page: page, per_page: per_page)
  end

  def show
    @blogs = @obj.blogs.paginate(page: params[:page])
  end

  def new
    @obj = User.new
  end

  def create
    flag = true
    e_notice = nil
    begin
      # @obj = @model.create(permitted_params)
      @obj = @model.create!(permitted_params)
    rescue Exception => e
      @obj = @model.new(permitted_params)
      e_notice = e.message
      flag = false
    end
    err_msg = @obj.try(:errors).try(:messages).try(:values).try(:join, ',')

    flag = false if err_msg.present?

    if flag
      redirect_to user_path(@obj), notice: '注册成功！'
    else
      flash[:notice] = e_notice
      render 'new'
    end

  end

  def edit

  end

  private
  def set_user
    @obj = User.find(params[:id])
  end

  def permitted_params
    params.require(@model.model_name.singular.to_sym).permit(@model.column_names.map(&:to_sym) - %i(updated_at created_at) + %i(password password_confirmation))
  end
end
